<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            current-node-key=""
            highlight-current
            @node-click="handleNodeClick"
            empty-text="数据加载中"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="商品名称" prop="productName">
            <el-input
              v-model="queryParams.productName"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="品牌">
            <el-select
              v-model="queryParams.goodsBrandId"
              filterable
              clearable
              placeholder="请选择品牌"
            >
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.brandName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['supplier:localProduct:addPriGoods']"
              >新增</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              size="mini"
              :disabled="multiple"
              @click="handleAudit"
              v-hasPermi="['supplier:localProduct:audit']"
              >批量审核</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="multiple"
              @click="handleChangePrice"
              v-hasPermi="['commodity:product:batchChangePrice']"
              >批量改价</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="primary"
              v-hasPermi="['supplier:localProduct:export']"
              plain
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              v-hasPermi="['supplier:localProduct:pullGoods']"
              plain
              size="mini"
              @click="handlePull"
              >拉取商品</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <el-table
          v-loading="loading"
          :data="productList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            :selectable="isRowSelectable"
            width="50"
            align="center"
          />
          <el-table-column label="品牌" align="center" prop="goodsBrand">
            <template slot-scope="scope">
              <el-tag>{{ scope.row.goodsBrand }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="商品供应商"
            prop="showGoodsSupplier"
            align="center"
          >
            <!-- <template slot-scope="scope">
              <el-tag type="" effect="dark">{{
                scope.row.goodsSupplier
              }}</el-tag>
            </template> -->
          </el-table-column>

          <el-table-column label="商品名称" align="center" prop="productName" />

          <el-table-column label="供货价(元)" align="center" prop="shopPrice" />
          <el-table-column label="商品主图">
            <template slot-scope="scope">
              <el-image
                :src="scope.row.previewImg"
                fit="fill"
                style="width: 100px; height: 100px"
                :preview-src-list="[scope.row.previewImg]"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" prop="auditStatus">
            <template slot-scope="scope">
              <el-tag type="info" v-if="scope.row.auditStatus == 0"
                >待审核</el-tag
              >
              <el-tag type="success" v-else-if="scope.row.auditStatus == 1"
                >审核通过</el-tag
              >
              <el-tag type="danger" v-else-if="scope.row.auditStatus == 2"
                >审核拒绝</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="拒绝原因" align="center" prop="refusalReason">
          </el-table-column>

          <el-table-column
            label="本地设置库存数"
            align="center"
            prop="localInventory"
          >
            <template slot-scope="scope">
              {{ scope.row.localInventory }}
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['supplier:localProduct:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="handleDetail(scope.row)"
                v-hasPermi="['supplier:localProduct:detail']"
                >查看详情</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['supplier:localProduct:remove']"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleAddSpec(scope.row)"
                v-hasPermi="['supplier:localProduct:addSpec']"
                >添加规格</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 批量审核弹窗 -->
    <el-dialog
      title="批量审核"
      :visible.sync="auditOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="auditForm"
        :model="auditForm"
        :rules="auditRules"
        label-width="100px"
      >
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="-1">审核拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="审核原因"
          prop="refusalReason"
          v-if="auditForm.auditStatus == -1"
        >
          <el-input
            v-model="auditForm.refusalReason"
            placeholder="请输入审核原因"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="subLoading" type="primary" @click="submitFormAudit"
          >确 定</el-button
        >
        <el-button @click="auditOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改商城商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="价格模式" prop="priceModel">
          <el-radio-group v-model="form.priceModel">
            <el-radio :label="1">议价</el-radio>
            <el-radio :label="2">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="议价方式"
          prop="bargainId"
          v-if="form.priceModel == 1"
        >
          <el-select v-model="form.bargainId" placeholder="请选择议价方式">
            <el-option
              v-for="item in bargainList"
              :key="item.id"
              :label="item.bargainName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="自定义价格"
          prop="setProductShopPrice"
          v-if="form.priceModel == 2"
        >
          <el-input
            v-model="form.setProductShopPrice"
            placeholder="请输入自定义价格"
            onkeyup="value=value.replace(/[^\d]/g,'')"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否返现" prop="isCashBank">
          <el-radio-group v-model="form.isCashBank">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="返现方式"
          prop="cashBankId"
          v-if="form.isCashBank == 1"
        >
          <el-select v-model="form.cashBankId" placeholder="请选择返现方式">
            <el-option
              v-for="item in cashbackList"
              :key="item.id"
              :label="item.cashBankName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="subLoading" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拉取商品 -->
    <el-dialog title="拉取商品" :visible.sync="pullOpen" width="1200">
      <div>
        <el-form :model="sendChildMallList" label-width="80px">
          <!-- <el-form-item label="所属商城">
            <el-select
              v-model="sendChildMallList.childrenMallId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in mallList"
                :key="item.id"
                :label="item.mallName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-table
            :data="pullList"
            @selection-change="handleSelectionChildChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="品牌" align="center" prop="goodsBrand">
              <template slot-scope="scope">
                <el-tag>{{ scope.row.goodsBrand }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="商品供应商"
              prop="showGoodsSupplier"
              align="center"
            >
            </el-table-column>

            <el-table-column
              label="商品名称"
              align="center"
              prop="productName"
            />

            <el-table-column
              label="供货价(元)"
              align="center"
              prop="shopPrice"
            />
            <el-table-column label="商品主图">
              <template slot-scope="scope">
                <el-image
                  :src="scope.row.previewImg"
                  fit="fill"
                  style="width: 100px; height: 100px"
                  :preview-src-list="[scope.row.previewImg]"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="审核状态" align="center" prop="auditStatus">
              <template slot-scope="scope">
                <el-tag type="info" v-if="scope.row.auditStatus == 0"
                  >待审核</el-tag
                >
                <el-tag type="success" v-else-if="scope.row.auditStatus == 1"
                  >审核通过</el-tag
                >
                <el-tag type="danger" v-else-if="scope.row.auditStatus == 2"
                  >审核拒绝</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              label="本地设置库存数"
              align="center"
              prop="localInventory"
            >
              <template slot-scope="scope">
                {{ scope.row.localInventory }}
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="pullOpen = false">取 消</el-button>
        <el-button type="primary" :loading="subLoading" @click="submitPullForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPriList,
  addPriGoods,
  editPri,
  delProduct,
  category,
  updateIsShow,
  updateIsRecommend,
  changeLocalStockNum,
  showBankPriceList,
  changeSort,
  brandList,
  tagListAllPri,
  batchAudit,
  getProcessProductList,
  getCustomerShopList,
  checkGoodsToChildren,
} from "@/api/newGoods/goodsList";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Product",
  components: { Treeselect },
  data() {
    const numValidate = (rule, value, callback) => {
      if (value < 0) {
        return callback(new Error("自定义价格不得小于0元"));
      } else {
        return callback();
      }
    };
    return {
      //同步按钮加载
      syncLoad: false,

      subLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商城商品表格数据
      productList: [],
      productTagList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      adddeptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      categoryName: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        cateId: null,
      },
      //批量审核
      auditOpen: false,
      auditForm: {
        auditStatus: 1,
      },
      auditRules: {
        auditStatus: [
          { required: true, message: "请选择审核状态", trigger: "blur" },
        ],
        refusalReason: [
          { required: true, message: "请输入审核原因", trigger: "blur" },
        ],
      },
      //拉取商品
      pullOpen: false,
      pullList: [],
      sendChildMallList: {},
      mallList: [],
      //议价列表
      bargainList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cateId: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goodsBrandId: [
          { required: true, message: "请选择商品品牌", trigger: "blur" },
        ],
        marketPrice: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
        ],
        localStockNum: [
          { required: true, message: "请输入本地库存", trigger: "blur" },
        ],
        shopPrice: [
          { required: true, message: "请输入商城售价", trigger: "blur" },
        ],
        // previewImg: [
        //   { required: true, message: "请选择商品主图", trigger: "blur" }
        // ],
        // imgList: [
        //   { required: true, message: "请选择商品轮播图", trigger: "blur" }
        // ],

        details: [
          { required: true, message: "请输入商品详情", trigger: "blur" },
        ],
        isShow: [
          { required: true, message: "请选择是否上架", trigger: "blur" },
        ],
      },
      brandList: [],
      //返现列表
      showBankPriceList: [],
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getBrandList();

    // const mallId = this.$route.query.id;
    // if (mallId) {
    //   this.$store.dispatch("childMallLogin", { mallId }).then(() => {
    //     this.$store.dispatch("GenerateRoutes").then((accessRoutes) => {
    //       this.$router.addRouters(accessRoutes);
    //     });
    //   });
    // }
  },
  watch: {
    // 根据名称筛选部门树
    categoryName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    //提交拉取商品
    submitPullForm() {
      if (
        !this.sendChildMallList.mallProductIdList ||
        !this.sendChildMallList.mallProductIdList.length
      ) {
        this.$modal.msgError("请选择商品");
        return;
      }
      this.subLoading = true;
      checkGoodsToChildren(this.sendChildMallList)
        .then((res) => {
          this.subLoading = false;
          this.pullOpen = false;
          this.getList();
          this.$modal.msgSuccess(res.msg);
        })
        .catch((err) => {
          this.subLoading = false;
        });
    },
    // 拉取商品
    handlePull() {
      this.pullOpen = true;
      this.sendChildMallList = {
        mallProductIdList: [],
      };
      this.getPullList();
      // this.getMallList();
    },
    getMallList() {
      getCustomerShopList().then((res) => {
        this.mallList = res.data;
      });
    },
    getPullList() {
      getProcessProductList().then((res) => {
        this.pullList = res.data;
      });
    },
    // 多选框选中数据
    handleSelectionChildChange(selection) {
      this.sendChildMallList.mallProductIdList = selection.map(
        (item) => item.newMallProductId
      );
    },
    isRowSelectable(row) {
      console.log(row);
      return row.auditStatus != 1;
    },
    // 添加规格
    handleAddSpec(row) {
      const { id } = row;
      this.$router.push({
        path: "newGoodsSpec",
        query: {
          id,
        },
      });
    },
    getCashbackList() {
      showBankPriceList().then((res) => {
        this.cashbackList = res.data;
      });
    },
    /** 查询品牌列表 */
    getBrandList() {
      brandList().then((res) => {
        console.log(res);
        this.brandList = res.data;
      });
    },
    /** 查询应用场景列表接口 */
    getTagListAllPri() {
      tagListAllPri().then((res) => {
        console.log(res);
        this.productTagList = res.data;
      });
    },
    getImgUrlEdit(e) {
      this.form.previewImg = e;
    },
    getImgList(e) {
      console.log(e);
      this.form.imgList = e;
    },

    //提交商品库存
    submitFormNum() {
      this.$refs["num"].validate((valid) => {
        if (valid) {
          changeLocalStockNum(this.numForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.isNum = false;
            this.getList();
          });
        }
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      category().then((response) => {
        const all = { id: 0, label: "全部" };
        // let newData = this.handleTree(response.data, "productCategoryId");
        response.data.unshift(all);
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      console.log(data);
      this.queryParams.cateId = data.id;
      // this.queryParams.level = data.level;
      this.queryParams.level = 1;

      this.handleQuery();
    },
    /** 查询商城商品列表 */
    getList() {
      this.loading = true;
      const data = {
        ...this.queryParams,
        mallId: this.$route.query.id,
      };
      console.log(data);
      getPriList(data).then((response) => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productTag: [],
        isMember: 1,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 跳转详情
    handleDetail(row) {
      this.$router.push({
        path: "addGoods",
        query: {
          id: row.id,
          type: 2,
        },
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      console.log(this.ids);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.getTagListAllPri();
      // this.open = true;
      // this.title = "添加商城商品";
      // showAllCategoryPriList().then((response) => {
      //   this.adddeptOptions = this.handleTree(response.data, "id");
      // });
      this.$router.push({
        path: "addGoods",
      });
    },
    //批量审核
    handleAudit() {
      this.auditForm = {
        auditStatus: 1,
      };
      this.auditOpen = true;
    },
    //批量审核提交
    submitFormAudit() {
      this.$refs["auditForm"].validate((valid) => {
        this.subLoading = true;
        if (valid) {
          this.auditForm = {
            ...this.auditForm,
            productIds: this.ids,
          };
          batchAudit(this.auditForm)
            .then((response) => {
              this.$modal.msgSuccess("审核成功");
              this.auditOpen = false;
              this.getList();
              this.subLoading = false;
            })
            .catch(() => {
              this.subLoading = false;
            });
        }
      });
    },
    //批量改价
    handleChangePrice() {
      this.reset();
      this.open = true;
      this.getBargainList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.$router.push({
        path: "addGoods",
        query: {
          id: row.id,
        },
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.productTag.length >= 1) {
            this.form.productTag = this.form.productTag.toString();
          }
          if (this.form.id != undefined) {
            editPri(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPriGoods(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const mallProductId = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delProduct(mallProductId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "supplier/localProduct/export",
        {
          ...this.queryParams,
        },
        `product_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
